/*
 * @Author: zxc
 * @Date: 2020-07-23 12:07:43
 * @LastEditTime: 2020-07-23 12:22:46
 * @LastEditors: zxc
 * @Description: 本地存储
 */

const store = window.localStorage;

class LocalStores {
  /**
   * @Date: 2020-07-23 12:12:23
   *  如果value 是 object 会调用JSON.stringify 自动转换为字符串
   */
  //设置sotre
  public static set(key: string, value: any) {
    if (!store) return;
    let v = value;

    try {
      if (typeof value === "object") {
        v = JSON.stringify(v);
      }
      store.setItem(key, v);
    } catch (error) {
      //错误处理
    }
  }

  //获取sotre => 获取原始数据
  public static get(key: string) {
    if (!store) return;
    return store.getItem(key);
  }

  //获取同时转换josn
  public static getToJson(key: string) {
    if (!store) return;
    let data = store.getItem(key);
    if (data) {
      try {
        return JSON.parse(data);
      } catch (error) {
        //catch
      }
    } else return null;
  }

  //从本地删除
  public static remove(key: string) {
    if (!store) return;
    try {
      store.removeItem(key);
    } catch (error) {
      //catch
    }
  }
}

export default LocalStores;
